package com.example.springbootrabbitmq.cobfig;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author: wukangrong
 * @date: 2020/9/1 17:36
 * @description:
 */
@Component
@Slf4j
public class Producer implements  RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback{

    private RabbitTemplate rabbitTemplate;

    @Autowired
    public Producer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        //这是是设置回调能收到发送到响应
        rabbitTemplate.setConfirmCallback(this);
        //如果设置备份队列则不起作用
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnCallback(this);
    }

    @PostConstruct
    public void send() {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        log.info("correlationId:{}", correlationId);
        String message = LocalDateTime.now().toString();
        System.out.println("Sender:" + message);
        // 如果ruting_key 与配置中的exchange绑定不一致queue中不会缓存数据
        rabbitTemplate.convertAndSend("rabbit_exchange_test", "rabbit_routing_key_test", message, correlationId);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack){
            log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, true, cause);
        }else{
            log.info("消息发送失败:correlationData({}),ack({}),cause({})", correlationData, false, cause);
        }

    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}",exchange,routingKey,replyCode,replyText,message);
    }
}
